// 0. 获取元素
const nameIpt = document.querySelectorAll(".account-input")[0];
const pwdIpt = document.querySelectorAll(".account-input")[1];
const rpwdIpt = document.querySelectorAll(".account-input")[2];
const loginBtn = document.querySelector(".account-modify");
const nameSpan = document.querySelector(".nameSpan");
const pwd1Span = document.querySelector(".pwdSpan");
const pwd2Span = document.querySelector(".rpwdSpan");
const check = document.querySelector("#agreement");


// 2. 给账号 input 添加 change 事件
nameIpt.addEventListener("change", function () {
  nameSelect();
});

// 3. 给 注册 button 添加 click 事件
loginBtn.addEventListener("click", function () {
  register();
});

// 4. 验证账号是否重复请求
async function nameSelect() {
  let nameVal = document.querySelectorAll(".account-input")[0].value;
  // console.log(nameVal);

  const res = await pAjax({
    url: "../server/goods_select.php",
    method: "post",
    data: { userName: nameVal },
    dataType: "json",
  });
  // console.log(res);

  if (res.code === 1) {
    nameSpan.innerHTML = `<span style="color:green">${res.msg}</span>`;
  } else if (res.code === 0) {
    nameSpan.innerHTML = `<span style="color:red">${res.msg}</span>`;
  }
}

// 5. 注册账号的请求
async function register() {
  // 获取数据
  let nameVal = document.querySelectorAll(".account-input")[0].value;
  let pwd1Val = document.querySelectorAll(".account-input")[1].value;
  let pwd2Val = document.querySelectorAll(".account-input")[2].value;

  // 非空验证
  if (!nameVal || !pwd1Val || !pwd2Val) return alert("请完整填写表单");

  // 两次密码相同验证
  if (pwd1Val === pwd2Val) {
    pwd1Span.innerHTML = "";
  } else {
    pwd1Span.innerHTML = `<span style="color:red">您两次输入的密码不相同</span>`;
    return;
  }
  // 判断复选框是否勾选
  if (check.checked === false) {
    alert("请阅读并勾选协议");
    return;
  }

  // 发送注册请求
  const res = await pAjax({
    url: "../server/goods_register.php",
    method: "post",
    data: { userName: nameVal, userPwd: pwd1Val },
    dataType: "json",
  });

  // console.log(res);

  // 注册成功 提示5秒后跳转页面
  if (res.code === 1) {
    localStorage.id = res.id;

   alert('恭喜您注册成功,即将前往登录页面')
    window.location.href = "../pages/login.html?url=undefined";
  } else {
    alert("注册失败,请您根据提示重新尝试");
  }
}
